package com.cf.index.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Administrator
 */
@Controller
@PropertySource("classpath:config.properties")
public class FileController {

    @Value("${dir.upload}")
    private String uploadPath;

    /**
     * 多文件上传
     *
     * @param files 文件对象数组
     * @param req   HttpServletRequest
     * @param resp  HttpServletResponse
     * @return string
     */
    @PostMapping("upload")
    @ResponseBody
    public String upload(@RequestParam(value = "image", required = false) MultipartFile[] files, HttpServletRequest req, HttpServletResponse resp) {
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        for (MultipartFile file : files) {
            String originalName = file.getOriginalFilename();
            String suffixName = originalName.substring(originalName.lastIndexOf("."));
            String newName = UUID.randomUUID().toString() + suffixName;
            File targetFile = new File(uploadPath, newName);
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
                return "系统异常";
            }
        }
        return "上传成功";
    }

}
